package com.root.dreameraadmin.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.root.dreameraadmin.R;
import com.root.dreameraadmin.utils.HttpConnectionUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.root.dreameraadmin.view.ToolBarView.startIntroAnimation;

public class PointInfoActivity extends AppCompatActivity {


    @Nullable
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_text)
    TextView toolbar_textView;
    @Bind(R.id.ib_map)
    Button mapBtn;
    @Bind(R.id.id_bmapView)
    MapView mMapView; //百度地图控件
    @Bind(R.id.inputName)
    EditText inputNameText;

    private static final String TAG="PointInfoActivity";
    int point_id;
    String point_name;
    String point_longitude;
    String point_latitude;
    double longitude, newlongitude;
    double latitude, newlatitude;
    private BaiduMap baiduMap;  //百度地图对象
    private BMapManager manager;
    BitmapDescriptor bitmap;
    HashMap<String,Object> paramMap;
    private ProgressDialog proDia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_point_info);
        ButterKnife.bind(this);

        mapBtn.setVisibility(View.GONE);
        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, "编辑文物信息");

        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        point_id = bundle.getInt("point_id");
        point_name = bundle.getString("name");
        point_longitude = bundle.getString("longitude");
        point_latitude = bundle.getString("latitude");
        longitude =  Double.parseDouble(point_longitude);
        latitude =  Double.parseDouble(point_latitude);
        inputNameText.setText(point_name);

        baiduMap = mMapView.getMap();
        baiduMap.setOnMapLoadedCallback(callBackHandler);
        baiduMap.setOnMapClickListener(mapClickListener);

        manager = new BMapManager();
        manager.init();

        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker);
        ShowPoint(latitude, longitude, true);

        System.out.println("qwer id = " + point_id );
        System.out.println("qwer name = " + point_name );
        System.out.println("qwer lng = " + point_longitude );
        System.out.println("qwer lat = " + point_latitude );

    }


    /**
     * Map call back
     */
    BaiduMap.OnMapLoadedCallback callBackHandler  = new BaiduMap.OnMapLoadedCallback() {//回调函数
        @Override
        public void onMapLoaded() {
//            LatLng northeast = new LatLng(41.94892,123.725236); //东北角
//            LatLng southwest = new LatLng(41.618652,123.161532); //西南角
//            //设置地图显示范围
//            baiduMap.setMapStatusLimits(
//                    new LatLngBounds.Builder().include(northeast).include(southwest).build()
//            );
            baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(
                    new MapStatus.Builder().zoom(18).build()
            ));
            LatLng ll = new LatLng(latitude, longitude);
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(u);
        }
    };


    BaiduMap.OnMapClickListener mapClickListener = new BaiduMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng latLng) {
            baiduMap.clear();
            Log.d(TAG,"omMapClick");
            newlongitude = latLng.longitude;
            newlatitude = latLng.latitude;
            ShowPoint(newlatitude, newlongitude, false);
        }

        @Override
        public boolean onMapPoiClick(MapPoi mapPoi) {
            return false;
        }
    };


    public void ShowPoint(Double latitude,Double longitude,boolean flag) {

        // 定义marker坐标点
        LatLng point = new LatLng(latitude,longitude);
        //构建markerOption，用于在地图上添加marker
        OverlayOptions options = new MarkerOptions()//
                .position(point)// 设置marker的位置
                .icon(bitmap)// 设置marker的图标
                .zIndex(9);// 設置marker的所在層級
        // 在地图上添加marker，并显示
        baiduMap.addOverlay(options);

        //构建文字Option对象，用于在地图上添加文字
        OverlayOptions textOption = new TextOptions()//添加文字标注
            .position(point)
            .text(inputNameText.getText().toString())
            .fontSize(42)
            .fontColor(Color.rgb(0, 150, 64));
        //在地图上添加该文字对象并显示
        baiduMap.addOverlay(textOption);
    }

    @OnClick(R.id.ib_back)
    public void clickBack() {
        finish();
    }

    @OnClick(R.id.cancel_btn)
    public void cancelBtn() {
        clickBack();
    }

    @OnClick(R.id.submit_btn)
    public void cliskSubmit() {
        String name = inputNameText.getText().toString();
        if(name.equals("")){
            Toast.makeText(PointInfoActivity.this, "文物名称不能为空!", Toast.LENGTH_SHORT).show();
            return ;
        }
        new AlertDialog.Builder(PointInfoActivity.this)
                .setMessage("确定提交本次修改?")//设置显示的内容
                .setPositiveButton("确定", positiveListener)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        dialog.dismiss();
                    }
                }).show();
    }

    DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件



            paramMap = new HashMap<String, Object>();
            paramMap.put("id",point_id);
            paramMap.put("name", inputNameText.getText().toString());

            double submitlng = newlongitude == 0 ? longitude : newlongitude;
            double submitlat = newlatitude == 0 ? latitude : newlatitude;

            paramMap.put("longitude", submitlng);
            paramMap.put("latitude", submitlat);


            System.out.println("asdf id "+ point_id);
            System.out.println("asdf name "+ inputNameText.getText().toString());
            System.out.println("asdf lng "+ newlongitude);
            System.out.println("asdf lat "+ newlatitude);

            new updatePointInfoMask().execute();

        }
    };

    public class updatePointInfoMask extends AsyncTask<Void, Void, Void> {

        @Override
        protected  void onPreExecute() {
            proDia = new ProgressDialog(PointInfoActivity.this);
            proDia.setMessage("修改数据中...");
            proDia.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                HttpConnectionUtil.doPut(HttpConnectionUtil.PLACEURL + point_id + "/", paramMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void i) {
            System.out.println("asdf result "+ HttpConnectionUtil.result);
            if (HttpConnectionUtil.result == "success") {
                Toast.makeText(PointInfoActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
                paramMap.clear();
            } else{
                Toast.makeText(PointInfoActivity.this, "修改失败!", Toast.LENGTH_SHORT).show();
                paramMap.clear();
            }
            proDia.dismiss();
        }
    }

}
